package com.ai.networking.netty.client;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 *  蚂蚁舞
 */
@Slf4j
public class BootNettyClientChannelCache {
 
    public static volatile Map<String, BootNettyClientChannel> channelMapCache = new ConcurrentHashMap<String, BootNettyClientChannel>();
 
    public static void add(String code, BootNettyClientChannel channel){
    	channelMapCache.put(code,channel);
    }
 
    public static BootNettyClientChannel get(String code){
        return channelMapCache.get(code);
    }
 
    public static void remove(String code){
    	channelMapCache.remove(code);
    }

    public static void clientSendMessage(String code, String msg) {
        log.info("===========================  发送给PLC消息  ===========================");
        log.info("===========================  链路code：{} ===========================",code);
        log.info("===========================  发送消息内容:{} ===========================",msg);
        ByteBuf buf = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
        Channel channel = channelMapCache.get(code).getChannel();
        channel.writeAndFlush(buf);
        channel.flush();
    }

    /**
     * 当前建立过连接的所有信道，
     * 将这些数据追加到内存中，并通过key--value的形式进行存储
     * @param code
     * @param channel
     */
    public static void save(String code, BootNettyClientChannel channel) {
        if(channelMapCache.get(code) == null) {
            add(code,channel);
        }
    }
}